#coding:utf8
#
# Author: CMGS
# Created on 2011-1-18
#

import tinyurl
from libs.sqlpool import sqlPool as _pool

TABLE_NAME = 'rss'

def add(url = '', comment = '', provider = '', flag = 0, tags = []):
    sqlCmd = '''INSERT INTO %s(source, comment, provider, flag, tags) VALUES ('%s', '%s', '%s', '%d', '%s');'''
    sqlCmd = sqlCmd % (TABLE_NAME, url, comment, provider, flag, '|'.join(tags))
    ret = _pool.execute(sqlCmd)
    if ret != 1:
        return False
    return True

def mark(url):
    ret, tiny = tinyurl.add(url)
    if not ret:
        return False
    sqlCmd = '''UPDATE %s SET flag = '1', tiny = '%s' WHERE source = '%s'; ''' % (TABLE_NAME, tiny, url)
    ret = _pool.execute(sqlCmd)
    if ret != 1:
        return False
    return True

def delete(url):
    sqlCmd = '''DELETE FROM %s WHERE source = '%s'; ''' % (TABLE_NAME, url)
    ret = _pool.execute(sqlCmd)
    if ret != 1:
        return False
    return tinyurl.delete(url)

def getVaildSources():
    sqlCmd = '''SELECT * FROM %s WHERE flag = 1;''' % TABLE_NAME
    ret = _pool.query(sqlCmd, _pool.RET_DICT_ROW_FOR_KEY)
    return ret

def getSource(url):
    sqlCmd = '''SELECT * FROM %s WHERE source = '%s';''' % (TABLE_NAME, url)
    ret = _pool.query(sqlCmd, _pool.RET_DICT_ROW_FOR_KEY)
    if len(ret) > 0:
        return ret[0]
    return None

def isExist(url):
    ret = tinyurl.getTinyUrl(url)
    if ret is None:
        return False
    return ret

# Param Tags is List
def setTags(url, tags):
    oldTags = getTags(url)
    tags.extend(oldTags['tags'].split('|'))
    sqlCmd = '''UPDATE %s SET tags = '%s' WHERE source = '%s'; ''' % (TABLE_NAME, '|'.join(tags), url)
    ret = _pool.execute(sqlCmd)
    if ret != 1:
        return False
    return True

def getTags(url):
    sqlCmd = '''SELECT tags FROM %s WHERE source = '%s';''' % (TABLE_NAME, url)
    ret = _pool.query(sqlCmd, _pool.RET_DICT_ROW_FOR_KEY)
    if len(ret) > 0:
        return ret[0]
    return None

if __name__ == '__main__':
    add(u'http://www.cnbeta.com/backend', u'业界资讯站', u'ilskdw@gmail.com', tags = ['IT', 'News'])
    add(u'http://www.verycd.com/sto/feed', u'驴子下载站', u'ilskdw@gmail.com', tags = ['eMule'])
    mark('http://www.cnbeta.com/backend')
    print isExist('http://www.cnbeta.com/backend')
    print getVaildSources()
    print getSource('http://www.cnbeta.com/backend')
    print getTags('http://www.cnbeta.com/backend')
    setTags('http://www.cnbeta.com/backend', ['comment', 'digital'])
    print getTags('http://www.cnbeta.com/backend')
    delete('http://www.cnbeta.com/backend')
    delete('http://www.verycd.com/sto/feed')    
